using System;
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using Main.Details;
using Main.Event;
using Main.Inventory;
using UnityEngine;
using ZSW.Framework;

namespace Main
{
    public class AnimatorOverride : ZSWF_InitMonoBehaviour
    {
        [SerializeField] private SpriteRenderer holdItem;
        [SerializeField] private List<AnimationType> animationTypes;
        private Dictionary<string, Animator> animatorNameDic = new Dictionary<string, Animator>();

        public override void Init()
        {
            base.Init();
            foreach (var anim in GetComponentsInChildren<Animator>())
            {
                animatorNameDic.Add(anim.name, anim);
            }
        }

        private void OnEnable()
        {
            MainEventSystem.ItemSelectEvent += OnItemSelect;
            MainEventSystem.BeforeLoadSceneEvent += OnBeforeLoadScene;
            MainEventSystem.HarvestAtPlayerPositionEvent += OnHarvestAtPlayerPosition;
        }

        private void OnDisable()
        {
            MainEventSystem.ItemSelectEvent -= OnItemSelect;
            MainEventSystem.BeforeLoadSceneEvent -= OnBeforeLoadScene;
            MainEventSystem.HarvestAtPlayerPositionEvent -= OnHarvestAtPlayerPosition;
        }

        /// <summary>
        /// 切换场景时,切换为默认动画且头顶不再显示图标
        /// </summary>
        private void OnBeforeLoadScene()
        {
            holdItem.sprite = null;
            SwitchAnimator(PartType.None);
        }

        private void OnItemSelect(ItemDetails details, bool isSelected)
        {
            PartType partType = isSelected ? details.ItemType.ToPartType() : PartType.None;
            holdItem.sprite = partType == PartType.Carry ? details.ItemOnWorldSprite : null;
            SwitchAnimator(partType);
        }

        private void OnHarvestAtPlayerPosition(int itemId)
        {
            if (ZSWF_IOCContainer.Get<InventoryManager>().TryGetItemDetails(itemId, out var itemDetails) && holdItem.enabled)
            {
                StartCoroutine(ShowHarvestItem(itemDetails.ItemOnWorldSprite));
            }
        }

        private IEnumerator ShowHarvestItem(Sprite sprite)
        {
            holdItem.sprite = sprite;
            yield return new WaitForSeconds(0.8f);
            holdItem.sprite = null;
        }

        private void SwitchAnimator(PartType partType)
        {
            foreach (var animType in animationTypes)
            {
                if (partType == animType.partType)
                {
                    animatorNameDic[animType.partName.ToString()].runtimeAnimatorController = animType.controller;
                }
            }
        }
    }
}